package com.puff.jdbc.core;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import com.puff.framework.utils.PathUtil;

/**
 * 
 * @author dongchao
 *
 */
public class SqlConfigParser {

	private NodeParser nodeParser = new NodeParser();

	public void parser(InputStream in) {
		Document doc = nodeParser.parser(in);
		Node sqlconfignode = doc.getElementsByTagName("sqlconfig").item(0);
		parser(sqlconfignode);
	}

	public void parser(Node sqlconfignode) {
		NodeList children = sqlconfignode.getChildNodes();
		for (int i = 0; i < children.getLength(); i++) {
			Node node = children.item(i);
			if ("statements".equals(node.getNodeName().toLowerCase())) {
				NodeList statements = node.getChildNodes();
				for (int j = 0; j < statements.getLength(); j++) {
					Node statement = statements.item(j);
					if ("statement".equals(statement.getNodeName().toLowerCase())) {
						String tag = nodeParser.attr(statement, "tag");
						String clazz = nodeParser.attr(statement, "class");
						StatementBuilder.register(tag, clazz);
					}
				}
			}

			if ("sqlmap".equals(node.getNodeName().toLowerCase())) {
				String path = node.getAttributes().getNamedItem("path").getNodeValue();
				InputStream sqlmapin = null;
				try {
					if (path.startsWith("file:")) {
						sqlmapin = new FileInputStream(new File(path.replace("file:", "")));
					} else {
						sqlmapin = getClass().getClassLoader().getResourceAsStream(path.replace("classpath:", ""));
					}
					new SqlMapParser().parser(sqlmapin);
				} catch (Exception e) {
					throw new RuntimeException(e);
				} finally {
					if (sqlmapin != null) {
						try {
							sqlmapin.close();
						} catch (IOException e) {
							e.printStackTrace();
						}
					}
				}
			}
		}
	}

	public void reload() {
		parser(PathUtil.fromClassPath("db.xml"));
	}

}